import { URL_CLEVER } from "@/comm/api";
import { get } from "@/comm/request";
import { sortList } from "@/comm/tooler";
import { defineStore } from "pinia";
// import { useCapital } from "./capital";

interface IState {
	clevers: Array<any>;
	interval: string;
	chartType: string;
}

export enum ChartType {
	Area = "area",
	Solid = "candle_solid"
}

export const useClever = defineStore("clever", {
	state: (): IState => ({
		clevers: [],
		interval: "",
		chartType: ChartType.Solid
	}),

	getters: {},
	actions: {
		changeClevers(val: any) {
			this.clevers = val;
		},
		async changeInterval(val: string) {
			this.interval = val;
		},
		changeChartType(val: string) {
			this.chartType = val;
		},
		toggleChartType() {
			this.chartType = this.chartType == ChartType.Area ? ChartType.Solid : ChartType.Area;
		},
		async init() {
			let res: any = await get(URL_CLEVER, { limit: 10 });
			let ary = res.data || [];
			let temp: any = [];
			ary.forEach((i: { capitalInfoId: any }) => {
				let item = temp.find((o: { capitalInfoId: any }) => o.capitalInfoId == i.capitalInfoId);
				if (!item) {
					temp.push(i);
				}
			});
			this.clevers = temp;
		},
		updateData(item: any) {
			let n = this.clevers.findIndex(i => i.capitalInfoId == item.capitalInfoId);
			if (n != -1) {
				this.clevers[n] = item;
			} else {
				this.clevers.push(item);
			}
			console.log(
				"this.clevers before",
				this.clevers.map(i => i.capitalInfoId)
			);
			this.clevers.forEach(i => (i.lastActive = i.lastChangeToken.lastActive));
			sortList(this.clevers, "lastActive");
			console.log(
				"this.clevers after",
				this.clevers.map(i => i.capitalInfoId)
			);
			if (this.clevers.length > 10) {
				this.clevers.shift();
			}
		}
	}
});
